package com.song.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.song.eduservice.entity.EduSubject;
import com.song.eduservice.entity.excel.SubjectData;
import com.song.eduservice.service.EduSubjectService;

/**
 * @author song
 * @data 2020/3/29
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }


    /**
     * 读取excel内容 一行一行的读取
     *
     * @param subjectData
     * @param analysisContext
     */
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {

        if (subjectData != null) {
            EduSubject existOneSubject = this.existOneSubject(subjectData.getOneSubjectName(), eduSubjectService);
            //添加一级分类
            //没有相同的一级分类就添加
            if (existOneSubject == null) {
                existOneSubject = new EduSubject();
                existOneSubject.setParentId("0");
                existOneSubject.setTitle(subjectData.getOneSubjectName());
                eduSubjectService.save(existOneSubject);
            }

            //获取一级分类的ID值
            String pid=existOneSubject.getId();
            //添加二级分类
            EduSubject existTwoSubject = this.existTwoSubject(subjectData.getTwoSubjectName(), eduSubjectService, pid);
            if(existTwoSubject==null){
                existTwoSubject = new EduSubject();
                existTwoSubject.setParentId(pid);
                existTwoSubject.setTitle(subjectData.getTwoSubjectName());
                eduSubjectService.save(existTwoSubject);
            }
        }

    }

    /**
     * 判断一级分类不能重复添加
     *
     * @param name
     * @param eduSubjectService
     * @return
     */
    private EduSubject existOneSubject(String name, EduSubjectService eduSubjectService) {
        QueryWrapper<EduSubject> qw = new QueryWrapper();
        qw.eq("title", name);
        qw.eq("parent_id", 0);
        EduSubject oneSubject = eduSubjectService.getOne(qw);
        return oneSubject;
    }

    /**
     * 判断二级分类不能重复添加
     *
     * @param name
     * @param eduSubjectService
     * @param pid
     * @return
     */
    private EduSubject existTwoSubject(String name, EduSubjectService eduSubjectService, String pid) {
        QueryWrapper<EduSubject> qw = new QueryWrapper();
        qw.eq("title", name);
        qw.eq("parent_id", pid);
        EduSubject twoSubject = eduSubjectService.getOne(qw);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
